<template>
  <div>
    <div class="operate_wrap flex" style="margin-left: 25px">
      <div class="flex-center g-flex flex-right">
        <el-select class="select" size="small" v-model="search.enginType" v-on:change="getList()" value-key="id" placeholder="选择工程类型">
          <el-option v-for="(item,index) in selectList.enginTypeList" :key="index" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <!-- <el-select
          style="float: none; margin: 0; margin-right: 15px"
          class="select"
          size="small"
          v-model="search.projectStage"
          v-on:change="getList()"
          value-key="id"
          filterable
          placeholder="选择工程阶段"
        >
          <el-option
            v-for="(item,index) in selectList.projectStage"
            :key="index"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
        <el-upload class="daochu buildButtonStyle bidTable-import-button" action="" :before-upload="submitImportExcel">
          <el-button id="excel-import-button" class="delete" size="small" style="width: 0px;opacity:0;margin-left: -100px;"><i class="iconfont icon-icon_zp"></i> 导入excel
          </el-button>
        </el-upload>
        <!--        <el-button id="excel-import-button-out" class="daochu buildButtonStyle bidTable-import" size="small" style="width: 110px;margin-left:10px;" @click="importExcel"><i class="iconfont icon-icon_zp"></i> 导入excel-->
        <!--        </el-button>-->
        <!--        <el-button type="primary" size="small" class="daochu buildButtonStyle" round @click="exportExcel">-->
        <!--          <i class="iconfont icon-daochu"></i>&nbsp;导出-->
        <!--        </el-button>-->
      </div>

      <div class="flex-row" style="padding-right: 20px;" v-if="!showButtonSecond">
        <el-button type="primary" size="small" class="add buildButtonStyle" @click="showButtonGroup" v-permission="permission.edit">编辑计划时间
        </el-button>
        <el-button type="primary" size="small" class="add buildButtonStyle" @click="showAddDialog" v-permission="permission.add">项目设置
        </el-button>
      </div>
      <div class="flex-row" style="padding-right: 20px;" v-if="showButtonSecond">
        <el-button type="primary" size="small" class="add buildButtonStyle" @click="buttonAction('confirm')">确定
        </el-button>
        <el-button type="primary" size="small" class="add buildButtonStyle" @click="buttonAction('cancel')">取消
        </el-button>
      </div>
    </div>

    <div class="list_wrap WholeScroll" style="padding: 20px;">
      <el-table class="project-management-info" :border="true" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="list" tooltip-effect="dark" :height="tableHeight" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px">
        <el-table-column show-overflow-tooltip label="序号" type="index" fixed="left" width="50">
        </el-table-column>

        <el-table-column show-overflow-tooltip prop="projectName" align="left" fixed="left" width="140" label="项目名称">
          <template slot-scope="scope">
            <div class="row-new-line-css">
              <span>{{ scope.row.projectName }}</span>
              <div v-if="showButtonSecond">
                <i class="el-icon-caret-top" v-if="scope.$index != 0" @click="changeRowIndexEvent('top',scope.$index)"></i>
                <i class="el-icon-caret-bottom" v-if="scope.$index != list.length -1" @click="changeRowIndexEvent('bottom',scope.$index)"></i>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="项目概况">
          <el-table-column label="项目代码" align="left" prop="code" width="140"></el-table-column>
          <el-table-column label="技术标准" align="left" prop="standard" width="100"></el-table-column>
          <el-table-column label="建设规模（公里）" align="left" prop="constructionScale" width="140"></el-table-column>
          <el-table-column label="项目性质" align="left" prop="projectNature" width="100"></el-table-column>
        </el-table-column>
        <!-- 项们 -->
        <el-table-column v-for="(item,index) in itemlabelList[search.enginType]" :key="'itemlabelList'+index" :label="item.name" align="left" :prop="item.code" width="140">
          <template slot-scope="scope">
            <span class="tableRowSpan" v-show="!showButtonSecond">{{scope.row[item.code]}}</span>
            <el-date-picker v-if="showButtonSecond" v-model="scope.row[item.code]" type="date" style="width: 100%;" format="MM月dd日" value-format="yyyy-MM-dd" placeholder="选择日期">
            </el-date-picker>
          </template>
        </el-table-column>
        <!--  -->
        <el-table-column label="备 注" align="left" width="250">
          <template slot-scope="scope">
            <span class="tableRowSpan" v-show="!showButtonSecond">{{scope.row.mark}}</span>
            <el-input v-model="scope.row.mark" v-show="showButtonSecond" placeholder="请输入"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>
  </div>
</template>

<script>
import {
  tableRowStyleGol,
  tableCellStyleGol,
  tableHeaderCellStyleGol,
  doCreateObject
} from '@/utils/publicFun'
import { getCompanyTree, getListForWarWatch, saveWarWatchReport, importExcel, exportExcel, getAllApprovalDict } from '@/api/buss/frontProject'
import crudDict from '@/api/system/dict'
import msgUtil from '@/utils/msgUtil'
import { getToken } from "@/utils/auth";
import Moment from 'moment'
export default {
  name: 'weekReport',
  components: {
    Detail: require('./bidTable-detail/bidTable-detail').default
  },
  data() {
    return {
      permission: {
        add: ['100', '督战表:add'],
        show: ['100', '督战表:show'],
        edit: ['100', '督战表:edit'],
        del: ['100', '督战表:del'],
      },
      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      companyTree: [],
      list: [],
      postDetailData: {
        show: false,
        type: 'build',
        typeNmae: '新增',
      },
      showButtonSecond: false,
      selectList: {
        enginTypeList: [],
        projectStage: [],
      },
      search: {
        year: this.getNowTime(),
        postYear: '',
        subcontractName: '',
        pageIndex: 0,
        pageSize: 999,
        pageSum: 0,
        contractId: '',
        searchType: '', // 合同类型
        searchName: '', // 合同名称
        company: { children: [] },
        companyId: '',
        project: { children: [] },
        sectionId: '',
        enginType: '',
        projectStage: '',
      },
      labelStr: {},//字典数
      itemlabelList: {},//选项
    }
  },
  created() {
    // this.getProjectType()
    this.getEnginTypeList()
    this.getAllApprovalDict()
    // this.getCompanyTree(()=>this.getList())
    // this.setYearNum()
  },
  computed: {
    tableHeight: function () {
      return (window.innerHeight - 330) + 'px';
    }
  },
  methods: {
    // 获取字典数，填充项
    getAllApprovalDict() {
      this.itemlabelList = {
        'ff808081877818f501894d0f97540086': [],
        'ff808081877818f501894d0fb6c30087': [],
        'ff8080818bf1932a018bfa1c9647012f': []
      }
      getAllApprovalDict().then(res => {
        res.data.map(e => {
          //标签字典项
          this.$set(this.labelStr, e.approvalKey, e.approvalName)
          let obj = { name: e.approvalName, code: e.approvalKey }
          let labelA = ['ghxz', 'tdys', 'wwbh', 'yfklz', 'dzzhpg', 'shwdxpj', 'zjlyzm', 'gkpf', 'gkwb', 'gkzx', 'gkpsh', 'ccckwyys', 'cbsjpf', 'gspg', 'gssh', 'cbsjwb', 'cbsjzx', 'cbsjpsh', 'thlz', 'fhyxpj', 'stbcbg', 'hjyxpj', 'trqgxap', 'dcxkwyys', 'sgtpf', 'sgtsjwb', 'sgtsjzx', 'sgtsjps', 'ghydxkz', 'sgzb']
          let labelB = ['ghxz', 'tdys', 'shwdxpj', 'fahs', 'gkpf', 'gkwb', 'gkzx', 'cbsjpf', 'gspg', 'cbsjwb', 'cbsjzx', 'cbsjpsh', 'stbcbg', 'hjyxpj', 'fags', 'ghydxkz', 'ts', 'sgtsjwb2', 'xf', 'rf', 'jn', 'fl', 'gcghxkz', 'sgzb']
          let labelC = ['ghxz', 'tdys', 'shwdxpj', 'fahs', 'gkpf', 'gkwb', 'gkzx', 'cbsjpf', 'gspg', 'cbsjwb', 'cbsjzx', 'cbsjpsh', 'thlz', 'fhyxpj', 'stbcbg', 'hjyxpj', 'fags', 'ghydxkz', 'ghrkqzfazt', 'ts', 'sgtsjwb2', 'gcghxkz', 'sgzb']
          if (labelA.indexOf(e.approvalKey) !== -1) {//交通工程
            this.itemlabelList["ff808081877818f501894d0f97540086"].push(obj)
          }
          if (labelB.indexOf(e.approvalKey) !== -1) {//房建工程
            this.itemlabelList["ff808081877818f501894d0fb6c30087"].push(obj)
          }
          if (labelC.indexOf(e.approvalKey) !== -1) {//市政工程
            this.itemlabelList["ff8080818bf1932a018bfa1c9647012f"].push(obj)
          }
        })
      }).catch(e => {
        console.log("e=", e)
        msgUtil.error2("批复项字典获取失败", e)
      })
    },
    getProjectType() {
      crudDict.getByCode('project_stage').then(res => {
        if (res.code === 200) {
          this.selectList.projectStage = []
          var data = res.data;
          for (var i in data) {
            this.selectList.projectStage.push({ 'value': data[i].id, 'label': data[i].name });
          }
          if (this.selectList.projectStage.length > 0) {
            this.search.projectStage = this.selectList.projectStage[0].value
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取项目类型失败")
      })
    },
    getEnginTypeList() {
      crudDict.getByCode('enginType').then(res => {
        if (res.code === 200) {
          this.selectList.enginTypeList = []
          var data = res.data;
          for (var i in data) {
            this.selectList.enginTypeList.push({ 'value': data[i].id, 'label': data[i].name });
          }
          if (this.selectList.enginTypeList.length > 0) {
            this.search.enginType = this.selectList.enginTypeList[0].value
            this.getList()
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取工程类型失败")
      })

    },

    exportExcel() {
      exportExcel({ list: this.list }).then(res => {
        doCreateObject(res, '督战表.xlsx')
      })
    },
    //  导入excel
    importExcel() {
      //触发 文件选择的click事件
      $("#excel-import-button").trigger("click");
    },
    //  提交excel导入文件选择
    submitImportExcel(file) {
      let fd = new FormData()
      fd.append('file', file)
      fd.append('enginType', this.search.enginType)
      fd.append('projectStage', this.search.projectStage)
      fd.append('Content-Type', 'multipart/form-data; boundary=----WebKitFormBoundaryIOi8qEBAFV1KN25n')
      importExcel(fd).then(res => {
        if (res.data.status == 1) {
          console.log(`成功导入${res.data.data}条数据`)
          // this.$messageSuccess(`成功导入${res.data.data}条数据`)
          this.getList(true)
        } else {
          console.log("请求导入excel失败:" + res.data.message)
          // this.$messageError("请求导入excel失败:" + res.data.message)
        }
      }).catch(e => {
        console.log(e);
        // this.$messageError("请求导入excel失败")
      })
      // this.$httpPost(`${this.$store.state.httpHost.buss}/japi/${this.urlBussBase}/importExcel`, fd, {
      //   headers: {
      //     'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryIOi8qEBAFV1KN25n',
      //   }
      // }).then(res => {
      //   if (res.data.status == 1) {
      //     this.$messageSuccess(`成功导入${res.data.data}条数据`)
      //     this.getList(true)
      //   } else {
      //     this.$messageError("请求导入excel失败:" + res.data.message)
      //   }
      // }).catch(e => {
      //   console.log(e);
      //   this.$messageError("请求导入excel失败")
      // })
    },
    /**
     * 上传成功处理
     */
    uploadSuccess(response) {
      const code = response.code;
      if (code && code !== 200) {
        console.log("上次失败")
        // this.$message({
        //   message: response.msg,
        //   type: "error",
        // });
      } else {
        console.log("上传成功")
        // this.$message({
        //   message: "上传成功",
        //   type: "success",
        // });
      }
    },
    getList() {
      this.list.splice(0, this.list.length)
      getListForWarWatch(this.search).then((res) => {
        if (res.code === 200) {
          this.$set(this, 'list', res.data.content)
          this.$nextTick(() => {
            this.$refs['multipleTable'].doLayout()
          })
        } else {
          this.isLoading = false
          // this.$messageError(res.data.message)
        }
      })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.isLoading = false
          // this.$messageError(this.$route.name + '提交详情-请求失败')
        })
    },
    setYearNum() {
      //注意，当返回值是中国标准时间的格式时使用moment.js的时候一定要加上.utcOffset(480)，用来转换时区
      this.search.postYear = Moment(this.search.year).utcOffset(480).format("YYYY")
      console.log(this.search.postYear)
    },
    getNowTime() {
      return new Date();
    },
    getCompanyTree(callback) {
      getCompanyTree({}).then((res) => {
        // res.list.forEach(item=>{
        //   if('南阳方枣高速公路有限公司' === item.fullname){
        //     this.companyTree.push(item)
        //   }
        // })
        this.companyTree = res.list
        // this.search.company = res.list[0]
        this.search.company = this.companyTree[0]
        if (callback) callback()
      })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.isLoading = false
          // this.$messageError(this.$route.name + '提交详情-请求失败')
        })
    },
    // 修改行的序列
    changeRowIndexEvent(type, index) {
      if (type == 'top') {
        this.upGo(this.list, index)
      } else {
        this.downGo(this.list, index)
      }
    },
    // 向上移动一格
    upGo(fieldData, index) {
      if (index != 0) {
        fieldData[index].num = fieldData[index].num - 1
        fieldData[index] = fieldData.splice(index - 1, 1, fieldData[index])[0];
        fieldData[index].num = fieldData[index].num + 1
      } else {
        fieldData.push(fieldData.shift());
      }
    },
    // 向下移动一格
    downGo(fieldData, index) {
      if (index != fieldData.length - 1) {
        fieldData[index].num = fieldData[index].num + 1
        fieldData[index] = fieldData.splice(index + 1, 1, fieldData[index])[0];
        fieldData[index].num = fieldData[index].num - 1
      } else {
        fieldData.unshift(fieldData.splice(index, 1)[0]);
      }
    },
    buttonAction(type) {
      switch (type) {
        case 'submit':

          break;
        case 'confirm':
          this.showButtonSecond = false
          //这边调，后台的存数据接口
          saveWarWatchReport({ list: this.list }).then((res) => {
            console.log('保存成功', res)
            this.getList()

          })
            .catch((res) => {
              console.log('请求出现错误', res)
              this.isLoading = false
              // this.$messageError(this.$route.name + '提交详情-请求失败')
            })
          break;

        case 'cancel':
          this.showButtonSecond = false
          break
      }
    },
    showButtonGroup() {
      this.showButtonSecond = true
    },
    showAddDialog() {
      this.postDetailData = {
        show: true,
        type: 'build',
        typeName: '新增',
        companyId: this.search.company.id,
        enginType: this.search.enginType,
        projectStage: this.search.projectStage,
        list: this.list,
      }
    },
    // 切换列表
    paginationChange(index) {
      this.search.pageIndex = index - 1
      this.getList()
    },
  },
}
</script>

<style lang="scss" scoped>
.operate_wrap {
  .select {
    width: 250px;
    margin-right: 15px;
  }
}
.flex-row {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.row-new-line-css {
  display: flex;
  justify-content: space-between;
  align-items: center;
  i {
    cursor: pointer;
  }
}
</style>
